import { useEffect, useRef } from 'react';

export function useScrollWrap() {

  const el = useRef(null);

  //控制节点左右滚动
  let isDown = false;
  let startX;
  let scrollLeft;


  useEffect(() => {
    const scrollWrap = el.current;
    scrollWrap.addEventListener('mousedown', (e) => {
      isDown = true;
      scrollWrap.style.cursor = 'grab';
      startX = e.pageX - scrollWrap.offsetLeft;
      scrollLeft = scrollWrap.scrollLeft;
    });
    scrollWrap.addEventListener('mouseleave', () => {
      isDown = false;
      scrollWrap.style.cursor = 'auto';

    });
    scrollWrap.addEventListener('mouseup', () => {
      isDown = false;
      scrollWrap.style.cursor = 'auto';
    });

    scrollWrap.addEventListener('mousemove', (e) => {
      if (!isDown) return;
      e.preventDefault();
      const x = e.pageX - scrollWrap.offsetLeft;
      const walk = (x - startX) * 2; // 调整滚动速度，使其更顺畅
      scrollWrap.scrollLeft = scrollLeft - walk;
    });
    return () => {
      scrollWrap.removeEventListener('mouseDown', () => {});
      scrollWrap.removeEventListener('mouseleave', () => {});
      scrollWrap.removeEventListener('mouseup', () => {});
      scrollWrap.removeEventListener('mousemove', () => {});
    }
  }, []);

  return {
    el,
  };
}
